<script setup>
import { reactive, ref, onMounted } from 'vue';
import { page, deleteById } from "@/api/admin";
import { findById,page as findTotal } from "@/api/postInfo";
import { useRouter } from "vue-router";
const router = useRouter();
const queryPageParam = reactive({
  username: '',
  pageNo: 1,
  pageSize: 5
});
let hasRefreshed = false;

 const refreshOnce = () => {
  const router = useRouter();
  const { query } = router.currentRoute.value;
  
  // 如果已经刷新过或者URL中包含refreshed参数，则不再刷新
  if (hasRefreshed || query.refreshed === 'true') {
    return false;
  }
  
  hasRefreshed = true;
  
  // 添加refreshed参数并刷新页面
  router.replace({
    path: router.currentRoute.value.path,
    query: { ...query, refreshed: 'true' }
  });
  
  // 延迟刷新，确保路由参数生效
  setTimeout(() => {
    window.location.reload();
  }, 1);
  
  return true;
};
// 数据
const tableData = ref([]);
const total = ref(0);
const postTotal = ref(0);
// 在数据部分添加职位映射
const positionMap = ref({});
// 获取职位名称的方法
const getPositionName = async (positionId) => {
  if (!positionId) return '无职位';
  
  // 如果已经缓存过，直接返回
  if (positionMap.value[positionId]) {
    return positionMap.value[positionId];
  }
  
  try {
    const res = await findById(positionId);
    positionMap.value[positionId] = res.data.name; // 假设返回的字段是positionName
    return res.data.name;
  } catch (error) {
    console.error('获取职位信息失败:', error);
    return '未知职位';
  }
};
// 修改表格数据处理
const handleQueryPage = async () => {
  page(queryPageParam).then(async (res) => {
    console.log(res);
    tableData.value = res.data.records;
    total.value = res.data.total;
    
    // 预加载所有职位信息（可选）
    await Promise.all(
      tableData.value.map(async (item) => {
        if (item.employee?.positionId) {
          await getPositionName(item.employee.positionId);
        }
      })
    );
  });
   findTotal(queryPageParam).then(async (res) => {

    postTotal.value = res.data.total;
    console.log('---》',postTotal)
    
  });
};

const genderMap = reactive({
  1: '男',
  0: '女'
});
// 修改每页数量的回调函数
const handleSizeChange = (sizeValue) => {
  queryPageParam.pageSize = sizeValue;
  handleQueryPage();
};

// 修改页码之后的回调函数
const handleCurrentChange = (currentValue) => {
  queryPageParam.pageNo = currentValue;
  handleQueryPage();
};
const resetSearch = () => {
          queryPageParam.username = '';
          handleQueryPage();
        };
// 查看
const handleDetail = (id) => {
  router.push({
    path: '/admin/detail',
    query: { id }
  });
};

// 编辑
const handleEdit = (id) => {
  router.push({
    path: '/admin/save',
    query: { id }
  });
};

// 确认删除
const handleDeleteConfirm = (id) => {
  deleteById(id).then(() => {
    handleQueryPage(); // 删除成功后再次分页查询
  });
};

// 新增
const handleAdd = () => {
  router.push({
    path: '/admin/save'
  });
};

// Vue 挂载完成之后执行钩子函数
onMounted(() => {
  if (refreshOnce()) {
    // 刷新已触发，不执行后续逻辑
    return;
  }
    handleQueryPage();
});
</script>

<template>
 <div id="app">
    <div class="admin-container">
      <!-- 顶部标题区域 -->
      <div class="header">
        <div>
          <h1 class="header-title">
            <i class="fas fa-user-shield"></i>
            管理员管理系统
          </h1>
          <div class="header-subtitle">管理系统管理员账户与权限</div>
        </div>
        <div class="header-actions">
          <el-button type="primary" round @click="handleAdd">
            <i class="fas fa-plus"></i> 新增管理员
          </el-button>
        </div>
      </div>
      
      <!-- 统计卡片 -->
      <div class="stats-card">
        <div class="stat-item">
          <div class="stat-icon users">
            <i class="fas fa-users"></i>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ total }}</div>
            <div class="stat-label">管理员总数</div>
          </div>
        </div>
        
        <div class="stat-item">
          <div class="stat-icon active">
            <i class="fas fa-user-check"></i>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{total}}</div>
            <div class="stat-label">活跃管理员</div>
          </div>
        </div>
        
        <div class="stat-item">
          <div class="stat-icon positions">
            <i class="fas fa-briefcase"></i>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{postTotal}}</div>
            <div class="stat-label">职位类型</div>
          </div>
        </div>
      </div>
      
      <!-- 管理员列表卡片 -->
      <div class="card">
        <div class="card-header">
          <h2 class="card-title">
            <i class="fas fa-list"></i>
            管理员列表
          </h2>
          
          <div class="actions">
            <div class="search-box">
              <i class="fas fa-search"></i>
              <input 
                v-model="queryPageParam.username" 
                class="search-input" 
                placeholder="搜索用户名..."
                @keyup.enter="handleQueryPage"
              >
            </div>
            
            <el-button type="primary" round @click="handleQueryPage">
              <i class="fas fa-search"></i> 查询
            </el-button>
            
            <el-button type="info" round @click="resetSearch">
              <i class="fas fa-sync"></i> 重置
            </el-button>
          </div>
        </div>
        
        <!-- 管理员表格 -->
        <el-table :data="tableData" stripe style="width: 100%">
          <el-table-column prop="adminId" label="ID" width="80" sortable />
          <el-table-column prop="username" label="用户名" width="180" sortable />
          <el-table-column prop="password" label="密码" width="180">
          </el-table-column>
          <el-table-column prop="employee.name" label="姓名" width="180" />
          <el-table-column prop="employee.phone" label="电话" width="180" />
          <el-table-column prop="employee.gender" label="性别" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.employee.gender === 1" type="success">男</el-tag>
              <el-tag v-else type="danger">女</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="employee.position" label="职位" width="180">
            <template #default="scope">
              <el-tag type="info">
                {{ positionMap[scope.row.employee?.positionId] || getPositionName(scope.row.employee?.positionId) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="入职时间" width="180" sortable>
  <template #default="{ row }">
    {{ row.createTime ? row.createTime.replace('T', ' ') : '-' }}
  </template>
</el-table-column>
          <el-table-column label="操作" min-width="220" fixed="right">
            <template #default="scope">
              <div style="display: flex; gap: 10px;">
                <el-button 
                  class="action-button"
                  size="small" 
                  @click="handleDetail(scope.row.adminId)"
                >
                  <i class="fas fa-eye"></i> 查看
                </el-button>
                <el-button 
                  class="action-button"
                  type="primary" 
                  size="small" 
                  @click="handleEdit(scope.row.adminId)"
                >
                  <i class="fas fa-edit"></i> 编辑
                </el-button>
                <el-popconfirm 
                  title="确定要删除此管理员吗？" 
                  confirm-button-text="确定" 
                  cancel-button-text="取消"
                  @confirm="handleDeleteConfirm(scope.row.adminId)"
                >
                  <template #reference>
                    <el-button 
                      class="action-button"
                      type="danger" 
                      size="small"
                    >
                      <i class="fas fa-trash"></i> 删除
                    </el-button>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页控件 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="queryPageParam.pageNo"
            v-model:page-size="queryPageParam.pageSize"
            :page-sizes="[5, 10, 20, 30]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

body {
  background: linear-gradient(135deg, #f5f7fa 0%, #e4efe9 100%);
  min-height: 100vh;
  padding: 20px;
}

.admin-container {
  max-width: 1800px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 6px 20px rgba(0, 0, 150, 0.08);
  position: relative;
  overflow: hidden;
}

.header::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 8px;
  height: 100%;
  background: linear-gradient(to bottom, #409EFF, #64b5ff);
}

.header-title {
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-title i {
  color: #409EFF;
  font-size: 32px;
}

.header-subtitle {
  font-size: 16px;
  color: #7f8c8d;
  margin-top: 8px;
}

.stats-card {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
}

.stat-item {
  flex: 1;
  background: white;
  border-radius: 16px;
  padding: 25px;
  box-shadow: 0 4px 12px rgba(0, 0, 150, 0.05);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 150, 0.1);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  color: white;
}

.stat-icon.users {
  background: linear-gradient(135deg, #3498db, #64b5ff);
}

.stat-icon.active {
  background: linear-gradient(135deg, #2ecc71, #64d8a8);
}

.stat-icon.positions {
  background: linear-gradient(135deg, #9b59b6, #c8a2e0);
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
}

.stat-label {
  font-size: 16px;
  color: #7f8c8d;
  margin-top: 5px;
}

.card {
  background: white;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 6px 20px rgba(0, 0, 150, 0.08);
  margin-bottom: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.card-title {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 10px;
}

.card-title i {
  color: #409EFF;
}

.actions {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.search-box {
  display: flex;
  align-items: center;
  gap: 15px;
  background: #f8fafc;
  padding: 0 20px;
  border-radius: 12px;
  height: 48px;
  transition: all 0.3s ease;
}

.search-box:focus-within {
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.2);
}

.search-box i {
  color: #7f8c8d;
  font-size: 18px;
}

.search-input {
  border: none;
  background: transparent;
  height: 100%;
  width: 240px;
  outline: none;
  font-size: 15px;
  color: #2c3e50;
}

.el-table {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 150, 0.05);
  border: 1px solid #ebeef5;
}

.el-table :deep(.el-table__header) th {
  background-color: #f5f9ff;
  color: #409EFF;
  font-weight: 600;
}

.el-table :deep(.el-table__row) {
  transition: background-color 0.2s ease;
}

.el-table :deep(.el-table__row:hover) {
  background-color: #f8fafc !important;
}

.el-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.action-button {
  transition: all 0.2s ease;
}

.action-button:hover {
  transform: translateY(-2px);
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
}

.empty-state {
  text-align: center;
  padding: 50px 20px;
}

.empty-icon {
  font-size: 80px;
  color: #e0e6ed;
  margin-bottom: 20px;
}

.empty-text {
  font-size: 18px;
  color: #99a9bf;
  margin-bottom: 30px;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

@media (max-width: 992px) {
  .stats-card {
    flex-direction: column;
  }
  
  .actions {
    flex-direction: column;
    width: 100%;
  }
  
  .search-box {
    width: 100%;
  }
  
  .search-input {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 20px;
  }
  
  .header-actions {
    width: 100%;
  }
}
</style>